package anatex.kea.kea;

import java.util.*;

import org.apache.log4j.Logger;

import anatex.domain.Document;
import anatex.domain.TrainingDocument;

public class AttributesCalculator {

	List<TrainingDocument> trainigSet = null;
	Document document = null;
	ArrayList<ArrayList<String>> stemPhrases = null;
	ArrayList<CandidatePhrase> candidatePhrases = null;
	
	protected Double calculateMatchingDocumentsLog(String stemPhrase, int wordCount) {
		int documentCount = 0;
		Double log 	= 1d;
		
		for (TrainingDocument td : trainigSet) {
			if (td.getDocument().getId() == document.getId()) {
				continue;
			}
			
			if (Kea.getStemPhrases().get(td.getDocument().getId()).get(wordCount).contains(stemPhrase)) {
				documentCount ++;
			}
		}
		
		if (documentCount > 0) {
			log = - Math.log(documentCount / new Double(trainigSet.size()));
		}
		
		return log;
	}
	
	protected Double calculateTDxIDF(String stemPhrase, int wordCount) {
		Double TDxIDF 			= 0d;
		int occurences 			= 0;
		ListIterator<String> li = stemPhrases.get(wordCount).listIterator();
		
		while (li.hasNext()) {
			if (stemPhrase.equals(li.next())) {
				occurences ++;
			}
		}
		
		TDxIDF = new Double(new Double(occurences) / new Double(stemPhrases.get(wordCount).size())) * calculateMatchingDocumentsLog(stemPhrase, wordCount);
		
		return TDxIDF;
	}
	
	public void setTrainingSet(List<TrainingDocument> ts) {
		trainigSet = ts;
	}
	
	public void setDocument(Document doc) {
		document = doc;
	}
	
	public void setStemPhrases(ArrayList<ArrayList<String>> sp) {
		stemPhrases = sp;
	}
	
	public ArrayList<CandidatePhrase> calculateCandidatePhraseAttributes() {
		candidatePhrases = new ArrayList<CandidatePhrase>();
		
		for (int i = 1; i <= 3; i++ ) {
			int current = 0;
			int all = stemPhrases.get(i).size();
			
			for (String stemPhrase : stemPhrases.get(i)) {
				Double distance = new Double(current * i) / new Double(all * i);
				current ++;
				
				candidatePhrases.add(new CandidatePhrase(
						calculateTDxIDF(stemPhrase, i), distance, stemPhrase
					)
				);
			}
		}
		
		return candidatePhrases;
	}
	
}
